; (function (doc, storage, location, WebSocket) {

  // 获取需要的 dom 节点
  var oInput = doc.getElementsByTagName('input')[0];
  var oButton = doc.getElementsByTagName('button')[0];
  var oList = doc.getElementById('chat-list');

  // 创建一个 WebSocket 实例对象
  var ws = new WebSocket('ws:localhost:8000');
  var id = new Date().getTime();

  // 检验
  // console.log(oInput);
  // console.log(oButton);
  // console.log(oList);

  var init = () => {
    checkoutUsername();
    bindEvent();
  };

  function bindEvent() {
    oButton.addEventListener('click', handleSendClick, false);
    ws.addEventListener('open', handleWsOpen, false);
    ws.addEventListener('close', handleWsClose, false);
    ws.addEventListener('error', handleWsError, false);
    ws.addEventListener('message', handleWsMessage, false);
  };

  function handleSendClick() {
    console.log('FE：发送按钮点击');
    // 1. 获取到用户输入的内容
    var content = oInput.value.trim();
    var userName = storage.getItem('userName');
    var date = new Date();
    // 2. 判断输入内容是否合法
    if (!content) {
      alert('不能发送空的内容哦~');
      return;
    }
    // 3. 调用 WebSocket 的发送方法
    ws.send(JSON.stringify({
      id,
      userName,
      date,
      content
    }));

    // 4. 清空输入框内容
    oInput.value = '';
  }

  function handleWsOpen(event) {
    console.log('FE：WebSocket open');
    console.log(event);
  }

  function handleWsClose(event) {
    console.log('FE：WebSocket close');
    console.log(event);
  }

  function handleWsError(event) {
    console.log('FE：WebSocket error');
    console.log(event);
  }

  function handleWsMessage(event) {
    var data = JSON.parse(event.data);
    console.log(data);
    console.log('FE：WebSocket message');
    console.log(event);
    oList.innerHTML += addNodeLi(data);
  }

  function addNodeLi(data) {
    var { id, userName, date, content } = data;
    var node = `
    <li>
    <span>${userName}：</span><span>${content}</span>
    <p>${date}</p>
    <br />
    </li>
    `
    return node;
  }

  // 检验用户名是否存在
  function checkoutUsername() {
    var userName = storage.getItem('userName');
    if (!userName) {
      // 滚去登录
      location.href = '/login.html';
    }
  }

  // 初始化函数执行
  init();
})(document, localStorage, location, WebSocket);